//
//  TopDownloadedViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/3/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "TopDownloadedViewController.h"

#import "PostClass.h"

#import "Constant.h"

#import "JsonClass.h"

#import "ParserClass.h"

#import "TopDownloadTableViewCell.h"

#import "TopDownloaded.h"

#import "UIManager.h"

#import "DownloadedSongs.h"

#import "FTWAPI.h"

#import "UserDetails.h"

@interface TopDownloadedViewController (){
    
    FTWAPI *ftwApi;
}

@end

@implementation TopDownloadedViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (!ftwApi) {
        ftwApi = [FTWAPI sharedInstance];
    }
    
    // Do any additional setup after loading the view from its nib.
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
    [self.navigationController.navigationBar setHidden:YES];
    
    dispatch_async(kBgQueue, ^{
        
        self.activityLoader.hidden = NO;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.activityLoader.hidden = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelArtistFeeds" object:@"cancelArtist"];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelTopsDL" object:nil];
            
            UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
            
            self.receivedData = [NSMutableData data];
            NSURLRequest *request = [[PostClass sharedItems] getTops:[UIDevice currentDevice].identifierForVendor.UUIDString andUserID:[userDetails idUser]];
            _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
            
        });
    });
    
    [self setupPullToRefresh];
    
}


-(void)setupPullToRefresh
{
    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tableView;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}
-(void)refreshTable{
    
    [self.tableView reloadData];
    
}


-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);

    [self.theConnection cancel];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(void)userProfile{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

- (IBAction)userProfileAction:(id)sender{

    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] topDownloadeds] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }
    
    
    static NSString *cellIdentifier = @"Cell";
    
    TopDownloadTableViewCell *cell = (TopDownloadTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TopDownloadTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    TopDownloaded *topDownloaded = [[ParserClass sharedItems] topDownloadeds][indexPath.row];

    cell.nameLbl.text = [topDownloaded songName];
    cell.downloads.text = [NSString stringWithFormat:@"Downloads: %@", [topDownloaded downloads]];
    cell.lblArtistName.text = [topDownloaded downloadedArtistName];
    
    @autoreleasepool {
        
        
        [cell.bgImg setAlpha:0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [topDownloaded albumImg]];
            
            [ftwApi setupCoverImage:cell.bgImg withURL:imageUrl];
            [cell.actLoading setHidden:YES];
            [cell.bgImg setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
        
    }
    
    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
            [cell.lblTop setText:@"1"];
            break;
            
        case 1:
            [cell.lblTop setText:@"2"];
            break;
            
        case 2:
            [cell.lblTop setText:@"3"];
            break;
            
        case 3:
            [cell.lblTop setText:@"4"];
            break;
            
        case 4:
            [cell.lblTop setText:@"5"];
            break;
            
        case 5:
            [cell.lblTop setText:@"6"];
            break;
            
        case 6:
            [cell.lblTop setText:@"7"];
            break;
            
        case 7:
            [cell.lblTop setText:@"8"];
            break;
            
        case 8:
            [cell.lblTop setText:@"9"];
            break;
            
        case 9:
            [cell.lblTop setText:@"10"];
            break;

        default:
            break;
    }
    
    return cell;
    
    
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"Song");
    
    
    TopDownloaded *topDownloaded = [[ParserClass sharedItems] topDownloadeds][indexPath.row];
    
    [[ParserClass sharedItems] getUrlSong:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [topDownloaded path]] andCount:indexPath.row andFileSize:[topDownloaded fileSize] andSongPreview:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [topDownloaded songPreview]]];
    [[ParserClass sharedItems] getImgStr:[topDownloaded albumImg]];
    
    [[ParserClass sharedItems] getType:@"TopDownloads"];
    
    [[ParserClass sharedItems] getArtistName:[topDownloaded downloadedArtistName]];
    
    [[ParserClass sharedItems] getAlbumName:[topDownloaded albumName]];
    
    [[ParserClass sharedItems] getAlbumID:[topDownloaded albumID]];
    
    [self.navigationController pushViewController:[[UIManager sharedItems] playSong] animated:YES];
    
}


#pragma mark - Fetched Data

- (void)fetchedData:(NSData *)responseData {
    
    NSMutableDictionary *json = [JsonClass jsonParser:responseData];
    
    [[ParserClass sharedItems] topDownloaded:json];
    
    [self.tableView reloadData];
    
    NSLog(@"top Download = %@", json);
}

- (void)viewDidUnload{
    
    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptyTopDownloaded];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            NSMutableDictionary *json = [JsonClass jsonParser:_receivedData];
            
            [[ParserClass sharedItems] topDownloaded:json];
            
            [self.tableView reloadData];
            
            NSLog(@"top Download = %@", json);

            
            
        }
        
        
        NSLog(@"Finish");
    }
    
}
@end
